package com.duoduo.selenium.demo;

import java.util.List;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;

import com.duoduo.selenium.util.SeleniumUtil;

/**
 * Selenium Webdriver元素定位的八种常用方式
 * 
 * <pre>
 * http://www.cnblogs.com/qingchunjun/p/4208159.html
 * 
 * <pre>
 * @author chengesheng@kedacom.com
 * @date 2017年3月16日下午3:58:52
 */
public class FindElementTest {

	public static void main(String[] args) {
		SeleniumUtil.setProperties();

		WebDriver driver = new FirefoxDriver();
		driver.get("https://www.baidu.com/");

		// 1、根据ID获取
		WebElement element = driver.findElement(By.id("kw"));
		element.click();
		element.clear();
		element.sendKeys("selenium java");

		// 2、根据name获取
		element = driver.findElement(By.name("wd"));
		System.out.println(element.getAttribute("value"));
		System.out.println();

		// 3、根据标签名获取
		List<WebElement> allInputs = driver.findElements(By.tagName("input"));
		for (WebElement e : allInputs) {
			if (e.getAttribute("id").equals("kw")) {
				System.out.println(e.getAttribute("value"));
			}
		}
		System.out.println();

		// 4、根据css类名获取
		List<WebElement> elements = driver.findElements(By.className("s_ipt"));
		for (WebElement e : elements) {
			if (e.getAttribute("id").equals("kw")) {
				System.out.println(e.getAttribute("value"));
			}
		}
		System.out.println();

		// 5、根据链接文本获取
		element = driver.findElement(By.linkText("新闻"));
		System.out.println(element.getAttribute("href"));
		System.out.println();

		// 6、根据部分链接文本获取
		element = driver.findElement(By.partialLinkText("新"));
		System.out.println(element.getAttribute("href"));
		element = driver.findElement(By.partialLinkText("闻"));
		System.out.println(element.getAttribute("href"));
		System.out.println();

		// 7、根据扩展路径获取
		element = driver.findElement(By.xpath("//span/input[@id='kw']"));
		System.out.println(element.getAttribute("value"));
		System.out.println();

		// 8、根据css选择器获取
		element = driver.findElement(By.cssSelector("span > #kw"));
		System.out.println(element.getAttribute("value"));

		driver.close();
	}
}
